﻿using Stateless;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Fake_Shop_WebApi.Models
{
    public class Order
    {
        public Order()
        {
            StateMachineInit();
        }
        [Key]
        public Guid Id { get; set; }
        public string UserId { get; set; }
        public ApplicationUser User { get; set; }
        public ICollection<LineItem> OrderItem { get; set; }
        public OrderStateEnum StateEnum { get; set; }
        public DateTime CreateDateUTC { get; set; }
        public string TransactionMetadata { get; set; }
        StateMachine<OrderStateEnum, OrderStateTriggerEnum> _machine;
        private void StateMachineInit()
        {
            _machine = new StateMachine<OrderStateEnum, OrderStateTriggerEnum>
                (OrderStateEnum.Pending);//生成订单
            _machine.Configure(OrderStateEnum.Pending)
                .Permit(OrderStateTriggerEnum.PlaceOrder, OrderStateEnum.Processing)//支付  状态变为 支付处理中
                .Permit(OrderStateTriggerEnum.Cancel, OrderStateEnum.Cancelled);//点击取消   状态变为 订单取消
            _machine.Configure(OrderStateEnum.Processing)
                .Permit(OrderStateTriggerEnum.Approve, OrderStateEnum.Completed)//支付成功  状态为交易成功
                .Permit(OrderStateTriggerEnum.Rejert, OrderStateEnum.Declined);//支付失败   状态为交易失败
            _machine.Configure(OrderStateEnum.Declined)
                .Permit(OrderStateTriggerEnum.PlaceOrder, OrderStateEnum.Processing);
            _machine.Configure(OrderStateEnum.Completed)
                .Permit(OrderStateTriggerEnum.Rejert, OrderStateEnum.Refund);
        }
    }
    public enum OrderStateEnum
    {
        Pending,//订单已生成
        Processing,//支付处理中
        Completed,//交易成功
        Declined,//交易失败
        Cancelled,//订单取消
        Refund,//已退款
    }
    public enum OrderStateTriggerEnum
    {
        PlaceOrder,//支付
        Approve,//支付成功
        Rejert,//支付失败
        Cancel,//取消
        Return,//退货
    }
}
